
#pragma once
#define SER_FIFO "fif0"

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

class NamedPipe
{
public:
    NamedPipe(const std::string &path, const std::string &name)
        : _path(path), _fifo_name(name)
    {
        _full_name = _path + "/" + _fifo_name;
        umask(0);
        // 1 创建命名管道
        if (mkfifo(_full_name.c_str(), 0666) < 0)
        {
            std::cerr << "mkfifo error" << std::endl;
            exit(1);
        }
        std::cout << "mkfifo success" << std::endl;
    }
    ~NamedPipe()
    {
        unlink(_full_name.c_str());
    }

private:
    std::string _fifo_name;
    std::string _path;
    std::string _full_name;
};

class File_operate
{
public:
    File_operate(const std::string &path, const std::string &name)
        : _path(path), _fifo_name(name), _fd(-1)
    {
        _full_name = _path + "/" + _fifo_name;
    }
    ~File_operate() {}
    void Open_for_Write()
    {
        _fd = open(_full_name.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void Open_for_Read()
    {
        _fd = open(_full_name.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            std::cerr << "open fifo error" << std::endl;
            return;
        }
        std::cout << "open fifo success" << std::endl;
    }
    void Write()
    {
        char c = 'A';
        ssize_t s = write(_fd, &c, 1);
    }
    bool Read()
    {
        char buffer;
        ssize_t s = read(_fd, &buffer, 1);
        if (s > 0)
            return true;
        return false;
        /*
        char buffer[1024];
         while (true)
       {
           ssize_t s = read(_fd, buffer, sizeof(buffer) - 1);
           if (s > 0)
           {
               buffer[s] = 0;
               std::cout << "client say:" << buffer << std::endl;
           }
           else if (s == 0)
           {
               std::cout << "all client closed" << std::endl;
               break;
           }
       }

       */
    }
    void Close()
    {
        if (_fd > 0)
        {
            close(_fd);
            _fd = -1;
        }
    }

private:
    std::string _fifo_name;
    std::string _path;
    std::string _full_name;
    int _fd;
};
